﻿var SelectareDimensiuniStructuriPage = function(pageContainer) {

    SelectareDimensiuniStructuriPage.superclass.constructor.call(this, pageContainer);

    var self = this;
    var currentCallback = null;

    var structuri = {};

    var dimensiuniToSelect = null;
    var isEditable = true;

    var Elements = {
        dimensiuniStructuriList: pageContainer.find(".dimensiuniStruncturiList"),
        renuntare: pageContainer.find(".renuntare"),
        salvare: pageContainer.find(".salvare"),
        costCenterButtons: pageContainer.find('.cost-center-buttons')
    };

    var Templates = {
        dimensiuniStructuriTemplate: pageContainer.find(".dimensiuniStructuriTemplate"),
        dimensiuniStructuriTemplateCompiled: null
    };

    self.initialize = override(self.initialize, function() {
        getDimensiuniStructuri();

        Elements.renuntare.tap(function() {
            app.goBack();
        });

        Elements.salvare.tap(function() {
            var input = getDimensionsInput();
            if (input)
                saveDimensionInput(input);
            else app.MessagesFactory.showToastWarning(translate('DimensiuniStructuri_NoDimensionSelected'));
        });

        pageContainer.bind('onBeforePageShow', function() {
            app.Phone.setBackbtnVisible(true);
        });
    });

    var getDimensiuniStructuri = function(callback) {
        app.showLoadingScreen();
        app.TMMService.Pontaj.GetDimensiuniStructuri(function(response) {
            var result = response.FinalResult;
            if (result && result.length > 0) {
                if (!Templates.dimensiuniStructuriTemplateCompiled) {
                    var source = Templates.dimensiuniStructuriTemplate.html();
                    Templates.dimensiuniStructuriTemplateCompiled = Handlebars.compile(source);
                }

                structuri = result;

                var html = "";
                for (var i = 0; i < result.length; i++)
                    html += Templates.dimensiuniStructuriTemplateCompiled(result[i]);
                Elements.dimensiuniStructuriList.append(html);
                Elements.dimensiuniStructuriList.find(".remove").tap(function() {
                    $(this).parents(".structura").find(".dimEntry").html(translate('General_Selectati'));
                    $(this).parents(".structura").find(".dimEntry").data("dimensiune", null);
                    $(this).hide();
                });

                Elements.costCenterButtons.show();

                if (dimensiuniToSelect)
                    self.setCentruCost(dimensiuniToSelect, isEditable);
                else app.hideLoadingScreen();

                setActionsDimensiuniStructuri();
            } else {
                app.MessagesFactory.showToastWarning(translate('General_EroareServer'));
                callback(null);
            }
            app.translatePage(app.Pages.SelectareDimensiuniStructuriPage);
        });
    };

    var setActionsDimensiuniStructuri = function() {
        Elements.dimensiuniStructuriList.find('.dimEntry').click(function(e) {
            var element = $(this);
            if (element.hasClass('disabled')) {
                if (!(app.User.Rights.ModificareCereriConcedii || app.User.Rights.ALL))
                    app.MessagesFactory.showToastInfo(translate('General_Info'), translate('Cerere_LipsaDreptModificare'));
                else app.MessagesFactory.showToastInfo(translate('General_Info'), translate('Cerere_FaraModificareCentruCost'));

                return;
            }

            var cstr_id = element.parents(".structura").attr("data-struct-id");
            var name = element.find('span').html();
            if (!app.Pages.SelectareDimensiuniPage.instance)
                app.Pages.SelectareDimensiuniPage.instance = new SelectareDimensiuniPage(app.Pages.SelectareDimensiuniPage.container);
            app.changePage(app.Pages.SelectareDimensiuniPage);
            app.Pages.SelectareDimensiuniPage.instance.setCallback(function(dim) {
                dimensiune = dim;
                element.html(dim.CVAL_NUME);
                element.data("dimensiune", dim);
                element.parents(".structura").find('img').show();
                app.changePage(app.Pages.SelectareDimensiuniStructuriPage);
            });
            app.Pages.SelectareDimensiuniPage.instance.refresh(cstr_id);

            return Event.stopEvent(e);
        });
    };

    var getDimensionsInput = function() {
        var input = "";
        var first = true;
        var found = false;
        Elements.dimensiuniStructuriList.find(".dimEntry").each(function() {
            var dim = $(this).data("dimensiune");
            if (!first)
                input += ".";
            else first = false;
            if (dim) {
                input += dim.CVAL_VALOARE;
                found = true;
            }
        });
        if (!found)
            return null;

        return input;
    };

    var saveDimensionInput = function(input) {
        app.showLoadingScreen();
        var dateStart = app.TMMData.Setari.RestrictionDate.format('yyyy.MM.dd');
        var dateEnd = new Date(9999, 0, 1).format('yyyy.MM.dd');
        app.TMMService.General.GetDimensionsEntries(input, dateStart, dateEnd, function(result) {
            app.hideLoadingScreen();
            if (result && result.Result && result.Result.FinalResult.CC_ID) {
                currentCallback(result);
            } else app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));
        });
    };

    this.setCallback = function(callback) {
        currentCallback = callback;
        reset();
    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone)
            app.Phone.setModuleAction(ModuleActions.None);
    });

    var reset = function() {
        Elements.dimensiuniStructuriList.find('.dimEntry').each(function() {
            var element = $(this);
            element.html(translate('General_Selectati'));
            element.removeData("dimensiune");
            element.parents(".structura").find('img').hide();
        });
    };

    this.setCentruCost = function(dimensiuni, editable) {
        isEditable = editable;
        if (!structuri.length) {
            dimensiuniToSelect = dimensiuni;
            return;
        }

        if (editable) {
            Elements.dimensiuniStructuriList.find('.dimEntry').removeClass('disabled');
            Elements.costCenterButtons.show();
        } else {
            Elements.dimensiuniStructuriList.find('.dimEntry').addClass('disabled');
            Elements.costCenterButtons.hide();
        }

        app.TMMService.Pontaj.GetDimensiuniAll(dimensiuni, function(response) {
            if (response.Exception)
                return app.MessagesFactory.showToastWarning(translate('General_Eroare'), translate('General_EroareServer'));

            reset();

            var index = 0;
            Elements.dimensiuniStructuriList.find('.dimEntry').each(function() {
                var element = $(this);
                var dim = response.FinalResult[index];
                if (dim) {
                    element.html(dim.CVAL_NUME);
                    element.data("dimensiune", dim);
                    if (editable)
                        element.parents(".structura").find('img').show();
                    else element.parents(".structura").find('img').hide();
                } else {
                    element.html(translate('General_Selectati'));
                    element.removeData("dimensiune");
                    element.parents(".structura").find('img').hide();
                }

                index++;
            });
        });

        dimensiuniToSelect = null;

        app.hideLoadingScreen();
    };

    self.initialize();
};
extend(SelectareDimensiuniStructuriPage, TMMobilePage);